<template>
  <div class="app-container">
    <search ref="searchRef" :roles="btnRoles" :search="handleSearch" :reset="handleReset"/>
    <div class="app-table">
      <el-table v-loading="state.loading" :data="tableState.records" border header-cell-class-name="table-header"
                @selection-change="handleSelectChange" height="100%" row-key="id"
                :tree-props="{ children: 'children', hasChildren: 'true' }"
      >
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
        <el-table-column type="selection" width="40" />
        <el-table-column v-for="(column, index) in columns" :key="index" :prop="column.dataIndex" :label="column.title" :align="column.align" :width="column.width" :show-overflow-tooltip="column.ellipsis">
          <template #default="scope">
            <template v-if="column.key === 'name'">
              <a>
                <svg-icon
                  v-if="scope.row.icon" :icon-class="scope.row.icon"
                  style="font-size: 14px; min-width: 14px; margin-right: 3px; "
                />
                {{ scope.row.name }}
              </a>
            </template>
            <template v-if="column.key === 'type'">
              <el-tag type="primary" v-if="scope.row.grade === 1">目录</el-tag>
              <el-tag type="success" v-else-if="scope.row.grade === 2">菜单</el-tag>
              <el-tag type="warning" v-else>按钮</el-tag>
            </template>
            <template v-if="column.key === 'enable'">
              <el-tag type="success" v-if="scope.row.enable">启用</el-tag>
              <el-tag type="warning" v-else>禁用</el-tag>
            </template>
            <template v-if="column.key === 'operation'">
              <div class="permission-btn">
                <div  v-for="(item, index) in rowBtnRoles" :key="index" v-permission="item.permission">
                  <a @click="item.onClick(scope.row)" v-if="scope.row.grade !== 3 || item.permission !== DeptApi.permission.save">
                    <el-tooltip placement="top">
                      <template #content>
                        <span>{{ item.title }}</span>
                      </template>
                      <svg-icon v-if="item.svg" :icon-class="item.icon"/>
                      <el-icon v-else size="16px">
                        <component :is="proxy.$icons[item.icon]" :style="{'color': item.color}"/>
                      </el-icon>
                    </el-tooltip>
                  </a>
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      class="app-page"
      v-model:current-page="pageSearch.pageNumber"
      v-model:page-size="pageSearch.pageSize"
      :page-sizes="commonState.pageSizes"
      :layout="commonState.layout"
      :total="tableState.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
    <detail :id="currentId" :drawer="formVisible" ref="formModuleRef" @refreshData="handleRefreshData"/>
  </div>
</template>
<script setup>
import Search from '@/views/system/dept/components/Search.vue';
import Detail from '@/views/system/dept/components/Detail.vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import {DeptApi} from '@/api/system/dept';
import {columns, pageSearch, state, setLoading, tableState, setSearchParam} from './index'
import {Utils} from '@/utils/index';
import {ref} from "vue";
import { commonState } from '@/common/index.js'
import SvgIcon from "@/components/SvgIcon/index.vue";
import {confirm} from "@/utils/confirm.js";

const {proxy} = useCurrentInstance();
//弹窗
const formVisible = ref(false);
const currentId = ref('');
const formModuleRef = ref();
const parentInfo = ref({});
//查询
const searchRef = ref()

//功能按钮
const btnRoles = [
  {
    btnName: '新增',
    icon: 'CirclePlus',
    onClick: handleAdd,
    permission: DeptApi.permission.save,
    type: 'success'
  },
  {
    btnName: '删除',
    icon: 'Delete',
    onClick: handleDelete,
    permission: DeptApi.permission.delete,
    type: 'danger'
  }
];
//列功能按钮
const rowBtnRoles = [
  {
      icon: 'CirclePlus',
    title: '新增',
    onClick: handleAdd,
    permission: DeptApi.permission.save,
    color: 'var(--el-color-primary)'
  },
  {
    icon: 'Edit',
    title: '修改',
    onClick: handleUpdate,
    permission: DeptApi.permission.update,
    color: 'var(--el-color-primary)'
  },
  {
    icon: 'Delete',
    title: '删除',
    onClick: handleRowDelete,
    permission: DeptApi.permission.delete,
    color: 'var(--el-color-danger)'
  }
]

//新增
function handleAdd(row) {
  formVisible.value = true;
  currentId.value = '';
  nextTick(() => {
    formModuleRef.value.initInfo(true,row);
  })
}

//更新
function handleUpdate(row) {
  formVisible.value = true;
  currentId.value = row.id;
  nextTick(() => {
    formModuleRef.value.initInfo(false,row);
  })
}

//刷新页面
function handleRefreshData() {
  formVisible.value = false;
  parentInfo.value = {};
  currentId.value = '';
  pageSearch.pageNumber = 1;
  findPage();
}

//删除每行
function handleRowDelete(row) {
  confirm(proxy,"是否删除数据?", "warning").then((res) => {
    if (!res) return;
    DeptApi.delete({ids: [row.id]}).then(res => {
      if (res.success) {
        proxy.$message.success(res.message);
        findPage();
      }
    });
  }).catch(() => {
  })
}

//删除操作
function handleDelete() {
  if (state.selectedRowKeys.length === 0) {
    proxy.$message.warning('请先选择数据');
    return;
  }
  let ids = [];
  state.selectedRowKeys.map(item => ids.push(item.id));
  confirm(proxy,"是否删除选中数据?", "warning").then((res) => {
    if (!res) return;
    DeptApi.delete({ids: ids}).then(res => {
      if (res.success) {
        proxy.$message.success(res.message);
        findPage();
      }
    });
  }).catch(() => {
  })
}

//选中行
function handleSelectChange(selectedKeys) {
  state.selectedRowKeys = selectedKeys;
}

//切换分页
function handleSizeChange(pageSize) {
  pageSearch.pageSize = pageSize
  pageSearch.pageNumber = 1
  findPage()
}

//跳转指定页
function handleCurrentChange(pageNumber) {
  pageSearch.pageNumber = pageNumber
  findPage()
}

//分页查询
function findPage() {
  setLoading(true);
  DeptApi.findPage(setSearchParam())
      .then(res => {
        if (res.success) {
          tableState.totalCount = Number(res.data.totalCount);
          tableState.records = Utils.convertTreeData(res.data.records);
        }
      }).catch((error) => {
        console.log(error);
      }).finally(() => {
    setLoading(false);
  });
}

//搜索
function handleSearch() {
  findPage();
}

//查询条件重置
function handleReset() {
  searchRef.value.handleReset();
  findPage();
}

findPage();
</script>

<style scoped lang="scss">
:deep(.el-table__expand-icon>.el-icon ){
  color: var(--el-color-primary);
}
a {
  color: var(--el-color-primary) !important;
}
</style>
